package org.balthie.demo.jdk.util.concurrent.collections.deque;

import java.util.Deque;
import java.util.concurrent.LinkedBlockingDeque;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyRateLimiter {
    private static final Logger LOGGER = LoggerFactory.getLogger(MyRateLimiter.class);
    private final Deque<Long> queue;
    private long timeIntervalInMs;
    public MyRateLimiter(long timeIntervalInMs, int maxLimit) {
        this.timeIntervalInMs = timeIntervalInMs;
        this.queue = new LinkedBlockingDeque<Long>(maxLimit);
    }
    public boolean incrAndReachLimit(){
        long currentTimeMillis = System.currentTimeMillis();
        boolean success = queue.offerFirst(currentTimeMillis);
        if(success){
            //没有超过maxLimit
            return false;
        }
        synchronized (this){
            //queue is full
            long last = queue.getLast();
            //还在时间窗口内,超过maxLimit
            if (currentTimeMillis - last < timeIntervalInMs) {
                return true;
            }
            LOGGER.info("time window expired,current:{},last:{}",currentTimeMillis,last);
            //超过时间窗口了,超过maxLimit的情况下,重置时间窗口
            queue.removeLast();
            queue.addFirst(currentTimeMillis);
            return false;
        }
    }
}